package com.gjl.app.view.web.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.gjl.app.view.web.BaseAction;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.opensymphony.xwork2.Action;

public class LoginAction extends BaseAction{

	private static final long serialVersionUID = -2676603736794228231L;
	
	private static final String LOGOUT_URL = "logout_url";
	
	private static final String ADMIN = "admin";
	

	@Override
	public String execute() throws Exception {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		if (user == null || !userService.isUserLoggedIn()) {
			HttpServletResponse response = ServletActionContext.getResponse();
			String loginUrl = userService.createLoginURL("/login.action");
			response.sendRedirect(loginUrl);
			return null;
		} else {
			HttpServletRequest request = ServletActionContext.getRequest();
			HttpSession session = request.getSession();
			session.setAttribute(ADMIN, userService.isUserAdmin());
			return super.execute();
		}
		
	}
	
	public String logout() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		session.removeAttribute(LOGOUT_URL);
		return Action.SUCCESS;
	}
}
